package com.brkj.communityStudy;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.*;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.JsonReader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.brkj.communityStudy.model.DS_TopicContent;
import com.brkj.communityStudy.model.DS_TopicDetail;
import com.brkj.course.*;
import com.brkj.course.model.DS_CourseClassInfo;
import com.brkj.download.CourseDownloader;
import com.brkj.httpInterface.BaseAjaxParams;
import com.brkj.httpInterface.HttpInterface;
import com.brkj.httpInterface.NomalResult;
import com.brkj.main.R;
import com.brkj.model.DS_Comment;
import com.brkj.model.DS_Course;
import com.brkj.util.*;
import com.brkj.util.view.BaseActivity;
import com.brkj.util.view.BaseCoreActivity;
import com.brkj.util.view.WidgetAnim;
import com.dgl.sdk.view.NoSlipGridView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by colin.ding on 2014/5/19.
 */
public class TopicStudyDetailActivity extends BaseActivity{

    @ViewInject(id= R.id.commentListView)
    ListView commentListView;
    @ViewInject(id=R.id.commentEdit)
    EditText commentEdit;
    @ViewInject(id=R.id.submit,click="submitComment")
    Button submit;

    private View courseView;

    private CommentAdapter commentAdapter;
    protected List<DS_Comment> commentList = new ArrayList<DS_Comment>();
    private View lodingView;
    private String topicID;

    private TextView title;
    private TextView content;
    private TextView topicTime;
    private ImageView image;
    private NoSlipGridView courseGridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setAnimType(RIGHT_ENTER_LEFT_EXT);

        super.onCreate(savedInstanceState);

        setContentView(R.layout.course_detail);

        setActivityTitle("专题学习");
        setReturnBtn();
        setRightBtn(R.drawable.member_selector, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TopicStudyDetailActivity.this, TopicStudyDetailMemberActivity.class);
                intent.putExtra("topicID", topicID);
                startActivity(intent);
            }
        });

        topicID = getIntent().getStringExtra("topicID");

        initTopic();
        initLodingBar();
        showTopic();

        commentEdit.clearFocus();

        commentListView.addHeaderView(courseView);
        commentListView.addHeaderView(lodingView);

        commentAdapter = new CommentAdapter(TopicStudyDetailActivity.this, commentList);
        commentListView.setAdapter(commentAdapter);

        getComment();

    }

    private void initTopic() {
        courseView = getLayoutInflater().inflate(
                R.layout.topic_detail_content, null, false);

        title = (TextView) courseView.findViewById(R.id.title);
        content = (TextView) courseView.findViewById(R.id.content);
        image = (ImageView) courseView.findViewById(R.id.image);
        courseGridView = (NoSlipGridView) courseView.findViewById(R.id.courseGrid);
        topicTime = (TextView) courseView.findViewById(R.id.topicTime);


    }
    private void initLodingBar() {
        lodingView = getLayoutInflater().inflate(
                R.layout.loding_bar, null, false);

    }

    private void showTopic() {

        BaseAjaxParams params = new BaseAjaxParams();
        params.put(HttpInterface.HIF_GetTopicDetail.params.topicID, topicID);

        FinalHttp fh = new FinalHttp();
        fh.post(HttpInterface.HIF_GetTopicDetail.address, params, new MyAjaxCallBack<Object>((BaseCoreActivity)this) {


            @Override
            public void onFailure(Throwable t, String strMsg) {
                // TODO Auto-generated method stub
                super.onFailure(t, strMsg);

                lodingView.setVisibility(View.GONE);
            }

            @Override
            public void onSuccess(Object t) {
                super.onSuccess(t);

                String jsonStr  = (String)t;

                Gson gson = new Gson();

//                DS_TopicDetail result;
//                result = gson.fromJson(jsonStr, DS_TopicDetail.class);

                try {
                    JSONArray jsonArray = new JSONArray(jsonStr);
                    JSONArray  jsonArray1 = jsonArray.getJSONArray(0);
                    JSONArray  jsonArray2 = jsonArray.getJSONArray(1);

                    Type listType = new TypeToken<List<DS_TopicContent>>(){}.getType();

                    List<DS_TopicContent> topicContentList  = gson.fromJson(jsonArray1.toString(), listType);

                    Type listType2 = new TypeToken<List<DS_Course>>(){}.getType();

                    List<DS_Course> courseList  = gson.fromJson(jsonArray2.toString(), listType2);

                    DS_TopicContent topicContent = topicContentList.get(0);

                    title.setText(topicContent.getName());
                    content.setText(topicContent.getContent());
                    topicTime.setText(topicContent.getTime());

                    ImgShow.display(image, topicContent.getImageUrl());

                    courseGridView.setAdapter(new CourseClassSecondAdapter(TopicStudyDetailActivity.this, courseList));


                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("获取数据错误");
                }


//                Gson gson = new Gson();
//                Type listType = new TypeToken<List<DS_Comment>>(){}.getType();
//                commentList  = gson.fromJson((String)t, listType);
//
//                if(commentList != null){
//                    getView(commentList);
//                }

                lodingView.setVisibility(View.GONE);
            }

        });

    }


    protected void getComment() {

        BaseAjaxParams params = new BaseAjaxParams();
        params.put(HttpInterface.HIF_GetTopicComment.params.topicID, topicID);

        FinalHttp fh = new FinalHttp();
        fh.post(HttpInterface.HIF_GetTopicComment.address, params, new AjaxCallBack<Object>() {


            @Override
            public void onFailure(Throwable t, String strMsg) {
                // TODO Auto-generated method stub
                super.onFailure(t, strMsg);

                lodingView.setVisibility(View.GONE);
            }

            @Override
            public void onSuccess(Object t) {
                super.onSuccess(t);

//				HIF_GetCourse.result result = JsonUtil.fromJson((String)t, HIF_GetCourse.result.class);

                Gson gson = new Gson();
                Type listType = new TypeToken<List<DS_Comment>>(){}.getType();
                commentList  = gson.fromJson((String)t, listType);

                if(commentList != null){
                    getView(commentList);
                }

                lodingView.setVisibility(View.GONE);
            }

        });

    }

    public void getView(List<DS_Comment> list){
        commentAdapter = new CommentAdapter(TopicStudyDetailActivity.this, list);
        commentListView.setAdapter(commentAdapter);
    }

    public void submitComment(View v){
        if(WidgetAnim.checkIfEmpty(this, commentEdit)){
            return;
        }

        BaseAjaxParams params = new BaseAjaxParams();
        params.put(HttpInterface.HIF_SubmitTopicComment.params.topicID, topicID);
        params.put(HttpInterface.HIF_SubmitTopicComment.params.UserID, MyApplication.myUserID);
        params.put(HttpInterface.HIF_SubmitTopicComment.params.UserHeadImg, MyApplication.myInfo.getHeadUrl());
        params.put(HttpInterface.HIF_SubmitTopicComment.params.CommentText, commentEdit.getText().toString());

        FinalHttp fh = new FinalHttp();
        fh.post(HttpInterface.HIF_SubmitTopicComment.address, params, new MyAjaxCallBack<Object>(this) {

            @Override
            public void onSuccess(Object t) {
                super.onSuccess(t);

                if(NomalResult.doResult((String)t, TopicStudyDetailActivity.this)){
                    showToast("发表评论成功！");
                    commentEdit.setText("");
                    getComment();

                    //隐藏键盘
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(commentEdit.getWindowToken(), 0); //强制隐藏键盘
                };

            }

        });
    }



    public class CourseClassSecondAdapter extends BaseAdapter{
        private ListItemView listItemView;
        protected LayoutInflater listContainer;
        private Context context;
        private List<DS_Course> courseList;

        public CourseClassSecondAdapter(Context context, List<DS_Course> courseList){
            this.context = context;
            this.courseList = courseList;

            listContainer = LayoutInflater.from(context);
        }

        private  class ListItemView{
            public TextView courseName;
        };

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return courseList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // 自定义视图
            listItemView = new ListItemView();
            // 获取list_item布局文件的视图
            if (convertView == null) {
                convertView = listContainer.inflate(R.layout.topic_detail_content_course_item, null);
                // 获取控件对象
                listItemView.courseName = (TextView) convertView.findViewById(R.id.courseTitle);

                // 设置控件集到convertView
                convertView.setTag(listItemView);
            } else {
                listItemView = (ListItemView) convertView.getTag();
            }

            listItemView.courseName.setText(courseList.get(position).getTitle());

            convertView.setOnClickListener(new myOnclickListener(position));


            return convertView;
        }

        class myOnclickListener implements View.OnClickListener {
            private int position;

            public myOnclickListener(int position){
                this.position = position;
            }


            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CourseDetailActivity.class);

                intent.putExtra("course", courseList.get(position));
                context.startActivity(intent);

            }

        }
    }
}
